package cn.angis.system.service;

import cn.angis.common.constant.Constant;
import cn.angis.db.service.BaseService;
import cn.angis.system.dto.output.LoginOutput;
import cn.angis.system.mapper.UserMapper;
import cn.angis.system.model.*;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import org.beetl.sql.core.SQLReady;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.ProxyComponent;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 包名称：cn.angis.system.service
 * 类名称：SysUserService
 * 类描述：系统用户服务
 * 创建人：@author angis.cn
 * 创建日期： 2022/12/30 17:39
 */
@ProxyComponent
public class UserService extends BaseService<UserMapper, User> {

    @Inject
    private UserroleService userroleService;

    @Inject
    private UserpostService userpostService;

    @Inject
    private RoleresService roleresService;

    public User getByUserName(String userName) {
        return baseMapper.getSQLManager().executeQueryOne(new SQLReady("select * from sys_user where del_flag='0' and username=?", userName), User.class);
    }

    public void refreshUserByUserId(String userId) {
        SaSession session = StpUtil.getSessionByLoginId(userId, false);
        if (session != null) {
            List<String> roleAndResourceByUserId = roleresService.getRoleAndResourceByUserId(userId);
            LoginOutput loginOutput = session.getModel(Constant.SESSION_USER_KEY, LoginOutput.class);
            loginOutput.setResources(roleAndResourceByUserId);
            session.set(Constant.SESSION_USER_KEY, loginOutput);
        }
    }

    public List<String> getPostListByUserId(String userId) {
        return baseMapper.getSQLManager().lambdaQuery(Userpost.class)
                .andEq(Userpost::getUserId, userId)
                .select().stream().map(Userpost::getPostId)
                .collect(Collectors.toList());
    }

    public List<String> getRoleListByUserId(String userId) {
        return baseMapper.getSQLManager().lambdaQuery(Userrole.class)
                .andEq(Userrole::getUserId, userId)
                .select().stream().map(Userrole::getRoleId)
                .collect(Collectors.toList());
    }

}
